//自定义土司
function toast({ title = "", message = "", type = "info", duration = 2000 }) {
  const main = $("#toast");
  if (main) {
    // console.log(main);
    // const toast = document.createElement("div");
    const toast = $("<div>");
    // console.log(toast);
    // Auto remove toast
    const autoRemoveId = setTimeout(function () {
      main.children().remove();
    }, duration);

    // Remove toast when clicked
    toast[0].onclick = function (e) {
      if (e.target.closest(".toast__close")) {
        main.children().remove();
        clearTimeout(autoRemoveId);
      }
    };

    const icons = {
      success: "fa fa-check-circle",
      info: "fa fa-info-circle",
      warning: "fa fa-exclamation-circle",
      error: "fa fa-exclamation-circle",
    };
    const icon = icons[type];
    const delay = (duration / 1000).toFixed(2);

    toast.addClass("toast");
    toast.addClass(`toast--${type}`);
    toast.css(
      "animation",
      `slideInLeft ease .3s, fadeOut linear 1s ${delay}s forwards`
    );
    toast.html(`
                <div class="toast__icon">
                    <i class="${icon}"></i>
                </div>
                <div class="toast__body">
                    <h3 class="toast__title">${title}</h3>
                    <p class="toast__msg">${message}</p>
                </div>
                <div class="toast__close">
                    <i class="fa fa-times"></i>
                </div>
            `);
    main[0].append(toast[0]);
  }
}
//自定义弹窗
function dialog({ title = "", message = "" }, success, cancel) {
  const main = $(".dialog");
  const mask = $(".dialog-mask");

  if (main) {
    main.html(
      '<span class="dialog_close">&#x2715;</span>' +
        '<h2 class="dialog_title">' +
        title +
        "</h2>" +
        '<p class="dialog_content">' +
        message +
        "</p>" +
        '<button class="dialog_confirm">OK</button>'
    );
    var dialogClose = $(".dialog_close");
    var dialogConfirm = $(".dialog_confirm");

    dialogClose.on("click", function () {
      cancel();
      main.removeClass("dialog_active");
      mask.removeClass("dialog-mask_active");
    });
    dialogConfirm.on("click", function () {
      success();
      main.removeClass("dialog_active");
      mask.removeClass("dialog-mask_active");
    });
    // console.log(main);
    main.toggleClass("dialog_active");
    mask.toggleClass("dialog-mask_active");
  }
}
String.prototype.colorHex = function () {
  // RGB颜色值的正则
  var reg = /^(rgb|RGB)/;
  var color = this;
  if (reg.test(color)) {
    var strHex = "#";
    // 把RGB的3个数值变成数组
    var colorArr = color.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
    // 转成16进制
    for (var i = 0; i < colorArr.length; i++) {
      var hex = Number(colorArr[i]).toString(16);
      if (Number(colorArr[i]) < 16) {
        hex = "0" + hex;
      }
      strHex += hex;
    }
    return strHex;
  } else {
    return String(color);
  }
};
String.prototype.colorRgb = function () {
  // 16进制颜色值的正则
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 把颜色值变成小写
  var color = this.toLowerCase();
  if (reg.test(color)) {
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      var colorNew = "#";
      for (var i = 1; i < 4; i += 1) {
        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
      }
      color = colorNew;
    }
    // 如果只有五位的值，需变成六位，如：#10f0f => #010f0f
    if (color.length === 6) {
      // console.log(colorNew);
      color = "#0" + color.substring(1);
    }
    // 处理六位的颜色值，转为RGB
    var colorChange = [];
    for (var i = 1; i < 7; i += 2) {
      colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
    }
    return colorChange;
  } else {
    return color;
  }
};

String.prototype.isValidIP = function () {
  var reg =
    /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  return reg.test(this);
};

var optionsMap = {
  0: ["Color", "IMAGE"],
  1: ["x1", "x2", "x3", "x4", "x5", "x6", "x7"],
  2: ["AUTO", "OFF", "ON"],
  3: ["12h", "24h"],
  4: ["English", "中文"],
  5: ["HDMI1", "HDMI2", "HDMI3", "HDMI4", "MIC1", "MIC2", "PGM"],
  6: ["Line", "Mic"],
  7: ["MF", "AF"],
  8: ["Auto", "Manual", "ShutterPri", "IrisPri"],
  9: ["Auto", "Indoor", "Outdoor", "OnePushWB", "Auto2", "Manual"],
};
String.prototype.getOptions = function () {
  var list = optionsMap[Number(this)];
  var optionstring = "";
  for (let i = 0; i < list.length; i++) {
    optionstring +=
      '<option class="select-option" value="' +
      list[i] +
      '" >' +
      list[i] +
      "</option>";
  }
  return optionstring;
};
function getTime(type) {
  var date = new Date();
  return date.toLocaleString("en-GB", { hour12: type == 0 });
  // console.log(date.toLocaleString("chinese", { hour12: false }));
}
function getTimeArray() {
  var date = new Date();
  var year = date.getFullYear(); //获取年份
  var month = date.getMonth() + 1; //获取月份
  var day = date.getDate(); //获取日期
  var hour = date.getHours(); //获取小时
  var minute = date.getMinutes(); // 获取分
  var seconds = date.getSeconds(); //获取秒
  return (
    year + "," + month + "," + day + "," + hour + "," + minute + "," + seconds
  );
}
function addCanvasRect({ left, top, width, height, textValue }) {
  // console.log(height);
  var textFont = {
    fontSize: 20,
    width,
    height,
    fill: "#fff",
  };
  var text = new fabric.Text(textValue, textFont);
  // 矩形对象
  var rect = new fabric.Rect({
    fill: "transparent", // 填充色：透明
    stroke: "#fff", // 边框颜色
    strokeWidth: 1,
    width,
    height,
    strokeUniform: true, //边框宽度不随缩放改变
  });

  var group = new fabric.Group([rect, text], {
    top,
    left,
    borderColor: "rgb(57, 243, 57)",
    lockScalingFlip: true, // true时，对象不能通过缩放为负值来翻转
    id: textValue,
  });
  group.set("selectable", false);
  // 将矩形添加到画布上
  canvasPip.add(group);
  if (selectedLayer == textValue) {
    canvasPip.setActiveObject(group);
    canvasPip.bringToFront(group);
  }
}
function addCanvasChromaRect({ top, left, width, height }) {
  // 矩形对象
  var rect = new fabric.Rect({
    fill: "transparent", // 填充色：透明
    stroke: "#fff", // 边框颜色
    strokeWidth: 1,
    width,
    height,
    top,
    left,
    borderColor: "rgb(57, 243, 57)",
    lockScalingFlip: true, // true 时，对象不能通过缩放为负值来翻转
    strokeUniform: true,
    id: "chroma",
  });
  // 将矩形添加到画布上
  canvasChroma.add(rect);
}
function addCanvasAreamask({ top, left, width, height }) {
  canvasAreamask.clear();
  var rect = new fabric.Rect({
    fill: "transparent", // 填充色：透明
    stroke: "#fff", // 边框颜色
    strokeWidth: 1,
    width,
    height,
    top,
    left,
    borderColor: "rgb(57, 243, 57)",
    lockScalingFlip: true, // true 时，对象不能通过缩放为负值来翻转
    strokeUniform: true,
    id: "areamask",
  });
  // 将矩形添加到画布上
  canvasAreamask.add(rect);
}

function checkStreamInfo(index) {
  var ipaddress = "";
  if ($("#ipaddress-" + index).val() == "") {
    toast({
      title: $("#Sys_Language")[0].selectedIndex == 0 ? "Notice" : "提示",
      message:
        $("#Sys_Language")[0].selectedIndex == 0
          ? "Please enter the streaming address"
          : "请输入推流地址",
      type: "info",
      duration: 2000,
    });
    return "";
  }
  var ip = $("#ipaddress-" + index).val() + "";
  if (ip.substring(ip.length - 1) != "/") {
    ip = ip + "/";
  }
  if (index == "1") {
    if ($("input[name='r-group-1']:checked").attr("id").includes("custom")) {
      if ($("#streamkey-" + index).val() == "") {
        toast({
          title: $("#Sys_Language")[0].selectedIndex == 0 ? "Notice" : "提示",
          message:
            $("#Sys_Language")[0].selectedIndex == 0
              ? "Please enter the stream key"
              : "请输入串流密钥",
          type: "info",
          duration: 2000,
        });
        return "";
      }
      ipaddress = ip + "," + $("#streamkey-" + index).val() + "";
    } else {
      //默认地址推流方式---统一发送local
      ipaddress = "local,";
    }
  } else {
    //推流2默认自定义输入
    if ($("#streamkey-" + index).val() == "") {
      toast({
        title: $("#Sys_Language")[0].selectedIndex == 0 ? "Notice" : "提示",
        message:
          $("#Sys_Language")[0].selectedIndex == 0
            ? "Please enter the stream key"
            : "请输入串流密钥",
        type: "info",
        duration: 2000,
      });
      return "";
    }
    ipaddress = ip + "," + $("#streamkey-" + index).val() + "";
  }
  return ipaddress;
}

function readURL(input) {
  if (input.files && input.files[0]) {
    // console.log(input.files);
    var index = input.files[0].name.lastIndexOf(".");
    var ext = input.files[0].name.substr(index + 1);
    //区分上传的文件类型
    if (
      [
        "png",
        "jpg",
        "jpeg",
        "bmp",
        "gif",
        "webp",
        "psd",
        "svg",
        "tiff",
      ].indexOf(ext.toLowerCase()) != -1
    ) {
      reader.onload = function (e) {
        //图片预览功能
        $("#" + input.name + "Address").text("");
        $("#" + input.name + "Address").css(
          "background-image",
          "url(" + e.target.result + ")"
        );
        $("#" + input.name + "Address").hide();
        $("#" + input.name + "Address").fadeIn(650);
      };
      reader.readAsDataURL(input.files[0]);
    } else {
      const box = document.getElementById(input.name + "-box");
      // console.log(box.children);
      if (box.children.length > 2) {
        // 已选择的文件（HTML-Item）修改名字
        const item = box.children.item(2);
        item.innerHTML = input.files[0].name;
      } else {
        // 新增已选择的文件（HTML-Item）
        const item = document.createElement("div");
        item.classList.add("file-item");
        item.innerHTML = input.files[0].name;
        item.onclick = function () {
          fileDelete(input.name);
        };
        box.appendChild(item);
      }
      //升级按钮显示
      $("#" + input.name + "-load").hide();
      $("#" + input.name + "-subbox").show();
    }
  } else {
  }
}

function fileDelete(id) {
  $("input[name=" + id + "]")[0].value = "";
  const box = $("#" + id + "-box");
  box[0].children.item(2).remove();
  $("#" + id + "-subbox").fadeOut(300);
}

//参数设置---统一调用接口
function sendArg({ argId, argType, argValue }) {
  if (isConnect) {
    $.ajax({
      type: "POST",
      url: "/control",
      data: {
        type: "arg",
        argId,
        argType,
        argValue,
      },
      success: function (result) {
        // toast({
        //   title: "提示",
        //   message: "设置成功",
        //   type: "success",
        //   duration: 2000,
        // });
      },
    });
  }
}
